var ActivityId;
//调用富文本textarea控件
var editor = new Simditor({
	textarea: $('#JoinCondition'),
	toolbar: false,
});
var editor2 = new Simditor({
	textarea: $('#ActivityContent'),
	toolbar: false,
});
var editor3 = new Simditor({
	textarea: $('#PrizeContent'),
	toolbar: false,
});
var editor4 = new Simditor({
	textarea: $('#ConvertWay'),
	toolbar: false,
});


//调用日期控件
$('#startDate,#endDate').daterangepicker({
	singleDatePicker: true,
	startDate: moment(),
	format: 'YYYY-MM-DD'
});



//图片上传及预览控件
var checkimg=false;
$(".uploadpic").click(function() {
	$("#fileupload").click()
});
var formData = new FormData();

function setFile() {
	formData.append('Content-Type', 'multipart/form-data');
	formData.append('file', $('#fileupload')[0].files[0]);
	$(".img-tips").text($('#fileupload')[0].files[0].name);
	console.log($('#fileupload')[0].files[0]);
	imgPreview("fileupload", "previewimg");
	checkimg=true;
}


function imgPreview(a, b) {
	var docObj = document.getElementById(a);
	var dd = document.getElementById(b);
	dd.innerHTML = "";
	var fileList = docObj.files;
	for (var i = 0; i < fileList.length; i++) {
		dd.innerHTML += "<div style='float:left' > <img class='ChangePreviewPic' id='img" + i + "'  /> </div>";
		var imgObjPreview = document.getElementById("img" + i);
		if (docObj.files && docObj.files[i]) {
			//火狐下，直接设img属性
			imgObjPreview.style.display = 'block';
			imgObjPreview.style.width = '128px';
			imgObjPreview.style.height = '56px';
			//imgObjPreview.src = docObj.files[0].getAsDataURL();
			//火狐7以上版本不能用上面的getAsDataURL()方式获取，需要一下方式
			imgObjPreview.src = window.URL.createObjectURL(docObj.files[i]);
		} else {
			//IE下，使用滤镜
			docObj.select();
			var imgSrc = document.selection.createRange().text;
			alert(imgSrc)
			var localImagId = document.getElementById("img" + i);
			//必须设置初始大小
			localImagId.style.width = "128px";
			localImagId.style.height = "56px";
			//图片异常的捕捉，防止用户修改后缀来伪造图片
			try {
				localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
				localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
			} catch (e) {
				alert("您上传的图片格式不正确，请重新选择!");
				return false;
			}
			imgObjPreview.style.display = 'none';
			document.selection.empty();
		}

	}
	$('.ChangePreviewPic').unbind("click"); //移除click
	$(".ChangePreviewPic").click(function() {
		zxTips_picpreview({
			picUrl:$(this).attr("src"),
			id:"myid",
			myclass:"myclass",
		});
		});
	return true;
}


//保存表单
 $(".btn.btn-save").on('click', function() {
		zxTips_classic({
			Head:false,//是否存在头部
			ContentText:"是否将活动提交审核？",//提示内容
			Foot:true,//是否拥有底部
			FootCancel:true,//是否拥有底部取消按钮
			FootEnter:true,//是否拥有底部确认按钮
			clickEnter:function(){
				zxTips_classicClose();
				if(CheckForm())
				{
					zxTips_loading({
						loadicon:true,//是否添加加载图标（默认添加）
						loadtxt:"上传中"//加载图片的路径
					});

					SaveForm() ;
				}
				else{
					zxTips_short({txt:"请检查上传信息是否有误"});
				}
				
				}
				});
	}); 
 
 //检查表单格式是否符合要求
	 function CheckForm(){
		 var CheckInfo=true;
		 //判断活动名称是否为空
		if($(".input-theme").val()=="")
		 {
			$(".input-theme").next(".input-label-tips").text("活动名称不能为空");
			CheckInfo=false;
			}
		else{$(".input-theme").next(".input-label-tips").text("");}
		 //判断时间是否正确
		var day = new Date();
		var year = day.getFullYear();
		var month = day.getMonth() + 1; // 记得当前月是要+1的
		var dt = day.getDate();
		var today = month+"/"+dt+"/"+year;
		var beginDate=$("#startDate").val();  
		var endDate=$("#endDate").val();  
		var d1 = new Date(beginDate.replace(/\-/g, "\/"));  
		var d2 = new Date(endDate.replace(/\-/g, "\/")); 
		var d3 = new Date(today.replace(/\-/g, "\/")); 
		if(d1 >d2)  
		 {  
		 $("#startDate").next(".input-label-tips").text("开始时间不能大于结束时间");  
		 CheckInfo=false;
		 }
		else{$("#startDate").next(".input-label-tips").text("");}
		if(d2<d3)  
		 {  
		 $("#endDate").next(".input-label-tips").text("结束时间不能小于今天");  
		 CheckInfo=false;
		 }
		else{$("#endDate").next(".input-label-tips").text("");}
		/*if(!checkimg){
		 $("#fileupload").next(".input-label-tips").text("请提交图片");  
		 CheckInfo=false;
		}
		else{$("#fileupload").next(".input-label-tips").text("");}*/
		 return CheckInfo;
		
	 }
//提交表单
	var UrlEdit=DataURL+'bank/activity/updateActivityById';//保存活动接口
	function SaveForm(){
		 formData = new FormData($( "#uploadForm" )[0]);
//		formData.append('checkStatus', '1');
		formData.append('id', ActivityId);
	    var objData = {};
	    
/*	    for (var entry of formData.entries()){
	        objData[entry[0]] = entry[1];
	    }
	    console.log(objData);*/
	    
		$.ajax({
			type:"POST",
			url:UrlEdit,
			  data: formData,  
	          contentType: false,  
	          processData: false,  
			success:function(data){
				if(checkTokenError(data)){
				//console.log(data);
				zxTips_short({txt:data.description});
				zxTips_loadingend();
				setTimeout(function(){
					window.location.href=HostURL+"/activityManager/bankActivity";
				},1000);
				}
			},
	        error:function(data){
	        	zxTips_loadingend();
	            console.log(data)
	            zxTips_short({
	    			txt : "系统错误"
	    			});
	        }
		});
	}

	
	//请求返回值
	var Request = new Object();
	Request = GetRequest();
	$(".back-btn").click(function() {
		if(Request["back"]==1)
		{window.location.href=HostURL+"/activitymanager/reviewActivity";}	
		else if(Request["back"]==3)
			{window.location.href=HostURL+"/activityManager/NotApprovalActivity";}
		else {window.location.href=HostURL+"/activityManager/bankActivity";}
	});
	function GetRequest() {
	    var url = location.search; //获取url中"?"符后的字串
	    var theRequest = new Object();
	    if (url.indexOf("?") != -1) {
	        var str = url.substr(1);
	        strs = str.split("&");
	        for(var i = 0; i < strs.length; i ++) {
	            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
	        }
	    }
	    return theRequest;
	}
	
	
	//初始化表单
	init();
	function init(){
		var GetDataURL=DataURL+"bank/activity/getActivityById";
		var ActivityPostData={};//通过ID请求活动数据
		var ActivityGetData={};//获得活动数据
		$(".back-btn").click(function() {
			if(Request["back"]==1)
			{window.location.href=HostURL+"/activityManager/reviewActivity";}	
			else if(Request["back"]==3)
			{window.location.href=HostURL+"/activityManager/NotApprovalActivity";}
			else {window.location.href=HostURL+"/activityManager/bankActivity";}
		});
		var Request = new Object();
		Request = GetRequest();
		function GetRequest() {
		    var url = location.search; //获取url中"?"符后的字串
		    var theRequest = new Object();
		    if (url.indexOf("?") != -1) {
		        var str = url.substr(1);
		        strs = str.split("&");
		        for(var i = 0; i < strs.length; i ++) {
		            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
		        }
		    }
		    return theRequest;
		}
		ActivityPostData["id"]=Request["id"];
		ActivityId=Request["id"];
		$.ajax({
			type : "GET",
			url : GetDataURL,
			dataType : 'json',
			async : false,
			data : ActivityPostData,
			success : function(data) {
				if(checkTokenError(data)){
				//console.log(data.content.data.data);
				ActivityGetData = data.content.data.data;
				InputFrom(ActivityGetData);
				}
			},
	        error:function(data){
	            console.log(data)
	            zxTips_short({
	    			txt : "系统错误"
	    			});
	        }
		});
	}
	
	//导入数据
	function InputFrom(ActivityGetData){
		//formData.append('id',ActivityGetData.id);
		$(".input-theme").val(ActivityGetData.theme);
		$(".input-object").val(ActivityGetData.object);
		$(".input-date_start").val(format(ActivityGetData.dateStart));
		$(".input-date_end").val(format(ActivityGetData.dateEnd));
		$(".input-addr").val(ActivityGetData.addr);
		editor.setValue(ActivityGetData.criteria);
		editor2.setValue(ActivityGetData.content);
		editor3.setValue(ActivityGetData.prize);
		editor4.setValue(ActivityGetData.convertWay);
		$("#previewimg").html('<img class="PreviewPic"  src="'+ActivityGetData.picturePath+'" style="display: block; width: 128px; height: 56px;">')

	}
	//时间戳转换为字符串
	function add0(m){return m<10?'0'+m:m }
	function format(TimeC)
	{
	var time = new Date(TimeC);
	var y = time.getFullYear();
	var m = time.getMonth()+1;
	var d = time.getDate();
	var h = time.getHours();
	var mm = time.getMinutes();
	var s = time.getSeconds();
	return add0(m)+'/'+add0(d)+'/'+y;
	}  